package websocket

import (
	"fmt"
	"gitee.com/sdynasty/clever/peer"
	"github.com/gorilla/websocket"
	"net/http"
	"net/url"
)

var upgrader = websocket.Upgrader{
	// 允许跨域
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func Start(addr string, sessMgr *peer.SessionManager) error {
	urlObj, err := url.Parse(addr)
	if err != nil {
		panic(err)
		return fmt.Errorf("websocket url parse failed. url(%s) %v", addr, err)
	}
	if urlObj.Path == "" {
		err = fmt.Errorf("websocket start failed. expect path in url to listen addr:%s", addr)
		panic(err)
		return err
	}

	http.HandleFunc(urlObj.Path, func(w http.ResponseWriter, r *http.Request) {
		var (
			wsConn *websocket.Conn
			err error
		)
		// 完成握手
		if wsConn, err = upgrader.Upgrade(w, r, nil); err != nil {
			fmt.Printf("ws upgrader.Upgrade error:%v\n", err)
			return
		}

		// 与Session绑定, 启动读写
		sess := peer.NewSession(newConnection(wsConn, sessMgr))
		sessMgr.Add(sess)
		fmt.Printf("连接成功")
	})

	fmt.Printf("启动http服务,host:%s\n", urlObj.Host)
	err = http.ListenAndServe(urlObj.Host, nil)
	if err != nil {
		panic(err)
	}
	return err
}
